<template>
	<view class="container">
		<unicloud-db ref="udb" v-slot:default="{data, pagination, loading, hasMore, error}"
			:collection="collectionList">
			<view v-if="error">{{error.message}}</view>
			<view v-else-if="data">
				<!-- <uni-list>
          <uni-list-item v-for="(item, index) in data" :key="index" showArrow :clickable="true" @click="handleItemClick(item._id)">
            <template v-slot:body>
              <text> 
                {{item._id}}
              </text>
            </template>
          </uni-list-item>
        </uni-list> -->
				<view class="wrap">
					<u-radio-group style="flex-direction:column;">
						<view class="item" v-for="(item, index) in data" :key="index">
							<u-row>
								<u-col :span="1" v-if="choose">
									<u-radio @change="chgRadio(item.id)" :name="item.id"></u-radio>
								</u-col>
								<u-col :span="choose==true?11:12">
									<view class="top">
										<view class="name" style="font-size: 23px;">{{ item.name }}</view>
										<view class="phone" style="font-size: 23px;">{{ item.tel }}</view>
										<view class="tag" v-if="item.is_default">
											<text class="red"
												style="font-size: 13px;line-height: 23px;height: 23px;">默认</text>
										</view>
									</view>
									<view class="bottom">
										<!-- <span style="font-size: 17px;line-height: 40px; display: none;">{{getAddress(item.address[0].code)}}{{item.address_detial}}</span> -->
										<span
											style="font-size: 17px;line-height: 40px; ">{{item.address[0].text}}{{item.address_detial}}</span>
										<!-- <span style="font-size: 17px;line-height: 40px; ">{{item[0].name}{{item[0].children[0].name}}}{{}}</span> -->
										<u-icon name="edit-pen" :size="40" color="#999999" @click="toEditAddr(item._id)">
										</u-icon>
									</view>
								</u-col>
							</u-row>
						</view>
					</u-radio-group>
					<view class="addSite" @tap="toAddAddr">
						<view class="add">
							<u-icon name="plus" color="#ffffff" class="icon" :size="30"></u-icon>新建收货地址
						</view>
					</view>
				</view>
			</view>
			<uni-load-more :status="loading?'loading':(hasMore ? 'more' : 'noMore')"></uni-load-more>
		</unicloud-db>
		<!-- <button class="button" type="primary" @click="shareToggle"><text class="button-text">分享模版示例</text></button> -->

		<!-- 新增收货地址弹窗 -->
		<view> 
			<uni-popup ref="add" type="share" safeArea backgroundColor="#fff">
				<view class="uni-container" style="padding: 15px;">
					<uni-section title="新增收货地址" type="line"></uni-section>
					<uni-forms class="top" ref="form" :model="formData" validate-trigger="submit" err-show-type="toast">
						<uni-forms-item class="left" name="name" label="收件人" required>
							<uni-easyinput placeholder="收件人" v-model="formData.name"></uni-easyinput>
						</uni-forms-item>
						<uni-forms-item name="tel" label="联系电话" required>
							<uni-easyinput placeholder="联系电话" v-model="formData.tel"></uni-easyinput>
						</uni-forms-item>
						<uni-forms-item name="is_default" label="默认" required>
							<uni-data-checkbox v-model="formData.is_default"
								:localdata="formOptions.is_default_localdata"></uni-data-checkbox>
						</uni-forms-item>
						<uni-forms-item name="address" label="地址" required>
							<uni-data-picker self-field="code" parent-field="parent_code" v-model="formData.address"
								collection="opendb-city-china" field="code as value,name as text"></uni-data-picker>
						</uni-forms-item>
						<uni-forms-item name="address_detial" label="详细地址" required>
							<uni-easyinput placeholder="详细地址" v-model="formData.address_detial"></uni-easyinput>
						</uni-forms-item>
						<view class="uni-button-group">
							<button type="primary" class="uni-button" @click="submit">保存提交</button>
						</view>
					</uni-forms>
				</view>
			</uni-popup>
		</view>
		<!-- 修改收货地址弹窗 -->
		<view>
			<uni-popup ref="edit"  safeArea backgroundColor="#fff"> 
				<view class="uni-container" style="padding: 15px;">
					<uni-section title="修改收货地址" type="line"></uni-section>
					<uni-forms ref="form" :model="formData2" validate-trigger="submit" err-show-type="toast">
					  <uni-forms-item name="name" label="收件人" required>
					    <uni-easyinput placeholder="收件人" v-model="formData2.name"></uni-easyinput>
					  </uni-forms-item>
					  <uni-forms-item name="tel" label="联系电话" required>
					    <uni-easyinput placeholder="联系电话" v-model="formData2.tel"></uni-easyinput>
					  </uni-forms-item>
					  <uni-forms-item name="is_default" label="是否默认" required>
					    <uni-data-checkbox v-model="formData2.is_default" :localdata="formOptions2.is_default_localdata"></uni-data-checkbox>
					  </uni-forms-item>
					  <uni-forms-item name="address" label="地址" required>
					    <uni-data-picker self-field="code" parent-field="parent_code" v-model="formData2.address" collection="opendb-city-china" field="code as value,name as text"></uni-data-picker>
					  </uni-forms-item>
					  <uni-forms-item name="address_detial" label="详细地址" required>
					    <uni-easyinput placeholder="详细地址" v-model="formData2.address_detial"></uni-easyinput>
					  </uni-forms-item>
					  <view class="uni-button-group">
					    <button type="primary" class="uni-button" @click="submit2">保存修改</button>
						<button type="primary" style="margin-top: 8px; color: #b4a992; background-color:#fff;border-color: #b4a992;"
						 class="uni-button" @click="deleteAddress(formData2._id)">删除地址</button>
					</view>
					</uni-forms>
				</view>
			</uni-popup>
		</view>
	</view>
</template>

<script>
	import {
		validator
	} from '../../js_sdk/validator/t_shop_address.js';
	const db = uniCloud.database()
	const dbCollectionName = 't_shop_address';

	function getValidator(fields) {
		let result = {}
		for (let key in validator) {
			if (fields.indexOf(key) > -1) {
				result[key] = validator[key]
			}
		}
		return result
	}
	export default {
		data() {
			let formData = {
				"name": "",
				"tel": "",
				"is_default": null,
				"address": "",
				"address_detial": ""
			}
			let formData2 = {
			  "name": "",
			  "tel": "",
			  "is_default": null,
			  "address": "",
			  "address_detial": ""
			}
			return {
				myaddress: 'xiantan,',
				collectionList: [
					db.collection('t_shop_address').field('name,tel,is_default,address,address_detial').getTemp(),
					db.collection('opendb-city-china').field('_id,code,name as text').getTemp()
				],
				loadMore: {
					contentdown: '',
					contentrefresh: '',
					contentnomore: ''
				},
				choose: false,
				formData,
				formData2,
				formOptions: {
					"is_default_localdata": [{
							"text": "否",
							"value": 0
						},
						{
							"text": "是",
							"value": 1
						}
					]
				},
				formOptions2: {
				  "is_default_localdata": [
				    {
				      "text": "否",
				      "value": 0
				    },
				    {
				      "text": "是",
				      "value": 1
				    }
				  ]
				},
				rules: {
					...getValidator(Object.keys(formData))
				}
			}
		},
		onReady() {
			// this.$refs.form.setRules(this.rules)
		},
		onLoad(option) {
			if (option.choose) {
				this.choose = true
			}
		},
		onPullDownRefresh() {
			this.$refs.udb.loadData({
				clear: true
			}, () => {
				uni.stopPullDownRefresh()
			})
		},
		onReachBottom() {
			this.$refs.udb.loadMore()
		},
		methods: {
			deleteAddress(id){ 
				// console.log(id)
				uni.showLoading({
				  mask: true
				})
				db.collection(dbCollectionName).doc(id).remove()
					.then((res) => {
						uni.showToast({
							icon: 'none',
							title: '删除成功'
						})
						this.getOpenerEventChannel().emit('refreshData')
						this.$refs.udb.loadData({
							clear: true
						})
						setTimeout(() =>  500)
					})
					.catch((err) => {
						uni.showModal({
						  content: err.message || '请求服务失败',
						  showCancel: false
						})
					})
					.finally(() => {
						 uni.hideLoading()
					}) 
			},
			/**
			 * 获取表单数据
			 * @param {Object} id
			 */
			getDetail(id) {
			  uni.showLoading({
			    mask: true
			  })
			  db.collection(dbCollectionName).doc(id).field("name,tel,is_default,address,address_detial").get().then((res) => {
			    const data = res.result.data[0]
			    if (data) {
			      this.formData2 = data 
			    }
				this.$refs.udb.loadData({
					clear: true
				})
			  }).catch((err) => {
			    uni.showModal({
			      content: err.message || '请求服务失败',
			      showCancel: false
			    })
			  }).finally(() => {
			    uni.hideLoading()
			  })
			},
			toEditAddr(id){
				console.log('修改地址',id)
				// const id = id
				this.formDataId = id
				this.getDetail(id)
				this.$refs.edit.open()
			},
			submitForm(value) {
				// 使用 clientDB 提交数据
				return db.collection(dbCollectionName).add(value).then((res) => {
					uni.showToast({
						icon: 'none',
						title: '新增成功'
					})
					this.getOpenerEventChannel().emit('refreshData')
					this.$refs.udb.loadData({
						clear: true
					})
					setTimeout(() =>  500)
				}).catch((err) => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					})
				})
			},
			submit() {
				uni.showLoading({
					mask: true
				})
				this.$refs.form.validate().then((res) => {
					return this.submitForm(res)
				}).catch(() => {}).finally(() => {
					uni.hideLoading()
				})
			},
			submitForm2(value) {
			  // 使用 clientDB 提交数据
			  return db.collection(dbCollectionName).doc(this.formDataId).update(value).then((res) => {
			    uni.showToast({
			      icon: 'none',
			      title: '修改成功'
			    })
			    this.getOpenerEventChannel().emit('refreshData')
				this.$refs.udb.loadData({
					clear: true
				})
			    setTimeout(() =>  500)
			  }).catch((err) => {
			    uni.showModal({
			      content: err.message || '请求服务失败',
			      showCancel: false
			    })
			  })
			},
			submit2() {
				uni.showLoading({
					mask: true
				})
				this.$refs.form.validate().then((res) => {
					return this.submitForm2(res)
				}).catch(() => {}).finally(() => {
					uni.hideLoading()
				})
			},
			shareToggle() {
				this.$refs.add.open()
			},
			handleItemClick(id) {
				uni.navigateTo({
					url: './detail?id=' + id
				})
			},
			toAddAddr() {
				// 打开新增页面
				this.$refs.add.open()

				// uni.navigateTo({
				//   url: './add',
				//   events: { 
				//     refreshData: () => {
				//       this.$refs.udb.loadData({
				//         clear: true
				//       })
				//     }
				//   }
				// })
			},
			chgRadio(id) {
				uni.setStorageSync('chooseAddrId', id)
				this.$u.route({
					type: 'navigateBack',
					delta: 1
				})
				return true
			},
			getAddress(code) {
				console.log(code)
				//拼装查询条件  
				let query = '\"code==' + '\'' + code + '\'' + '\"'
				// let myaddress = ''
				// console.log(query)  
				db.collection('opendb-city-china')
					.get({
						getTreePath: {
							"startWith": query //查询具体code所对应的省市区  
						}
					})
					.then((res) => {
						const resdata = res.result.data
						this.myaddress = resdata[0].name + resdata[0].children[0].name + resdata[0].children[0]
							.children[0].name
						console.log(this.myaddress)
					})
					.catch((err) => {
						uni.showModal({
							content: err.message || '请求服务失败',
							showCancel: false
						})
					})
				// this.address = '湖南湘潭市岳塘区'
				// console.log(myaddress)
				return this.myaddress
			},
		}
	}
</script>

<style lang="scss" scoped>
	.popup-content {
			display:  flex;
			align-items: center;
			justify-content: center;
			padding: 15px;
			height: 50px;
			background-color: #fff;
		}
	.wrap {
		padding: 0rpx 30rpx;

		.item {
			width: 100%;
			padding: 40rpx 20rpx;

			.top {
				display: flex;
				font-weight: bold;
				font-size: 34rpx;

				.phone {
					margin-left: 60rpx;
				}

				.tag {
					display: flex;
					font-weight: normal;
					align-items: center;

					text {
						display: block;
						width: 60rpx;
						height: 34rpx;
						line-height: 34rpx;
						color: #ffffff;
						font-size: 20rpx;
						border-radius: 6rpx;
						text-align: center;
						margin-left: 30rpx;
						background-color: rgb(49, 145, 253);
					}

					.red {
						background-color: red
					}
				}
			}

			.bottom {
				display: flex;
				margin-top: 20rpx;
				font-size: 28rpx;
				justify-content: space-between;
				color: #999999;
			}
		}

		.addSite {
			display: flex;
			justify-content: space-around;
			width: 600rpx;
			line-height: 100rpx;
			position: absolute;
			bottom: 30rpx;
			left: 50%;
			bottom: 10px;
			transform: translate(-50%, -50%);
			background-color: #f9c116;
			border-radius: 60rpx;
			font-size: 30rpx;

			.add {
				display: flex;
				align-items: center;
				color: #ffffff;

				.icon {
					margin-right: 10rpx;
				}
			}
		}
	}
</style>
